package cn.z2huo.knowledge.concurrency.threadpool;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author z2huo
 */
@Slf4j
class ThreadPoolTest {

    public static void main(String[] args) {

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                1,
                2,
                120,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );

        executor.execute(() -> {
            log.info("first task, {}", Thread.currentThread().threadId());
            ThreadUtil.sleep(30, TimeUnit.SECONDS);
        });

        executor.execute(() -> {
            // 第二个任务被放入任务队列中，所以会延后 30 秒
            log.info("second task, {}", Thread.currentThread().threadId());
            ThreadUtil.sleep(30, TimeUnit.SECONDS);
        });

        executor.execute(() -> {
            log.info("third task, {}", Thread.currentThread().threadId());
            ThreadUtil.sleep(30, TimeUnit.SECONDS);
        });

        executor.execute(() -> {
            // 在主线程中执行
            log.info("fourth task, {}", Thread.currentThread().threadId());
            // 导致主线程阻塞
            ThreadUtil.sleep(40, TimeUnit.SECONDS);
        });

        // 主线程阻塞 40 秒之后，执行该方法
        executor.execute(() -> {
            log.info("fifth task, {}", Thread.currentThread().threadId());
        });

        executor.shutdown();
    }

}
